package view.servlet;

import entity.Attraction;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.AttractionService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 注意这个Servlet类无法合并到AdminServlet中去
 */
@WebServlet("/AddAttractionServlet")
public class AddAttractionServlet extends HttpServlet {
    private AttractionService attractionService;
    @Override
    public void init() throws ServletException {
        super.init();
        attractionService = new AttractionService();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //检查是否已经登录
        Object o = req.getSession().getAttribute("login_status");
        if(o==null || !o.equals(true)) return;

        req.setCharacterEncoding("UTF-8");
        //设置编码
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();

        //检查request中的内容是否为multipart类型
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        //上传文件的存储路径
        String uploadFilePath = req.getSession().getServletContext().getRealPath("upload/attractions/");
//        System.out.println(uploadFilePath);
        if(isMultipart){
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            //字段依次是名称，等级，价格，地点，开放时间，介绍，状态
            ArrayList<String> fieldList = new ArrayList<>();

            try {
                List<FileItem> items = upload.parseRequest(req);
                //遍历form中每个字段元素
                Iterator<FileItem> iter = items.iterator();
                String fileName = null;
                while(iter.hasNext()){
                    FileItem item = (FileItem) iter.next();
                    if(!item.isFormField()) { //文件表单字段
                        //获取文件名
                        fileName = item.getName();
                        if (fileName != null && !fileName.isEmpty()) {
                            File saveFile = new File(uploadFilePath, fileName);
                            item.write(saveFile);
                            out.print("景点添加成功");
                        }
                    }else{ //普通表单字段
                        fieldList.add(item.getString("UTF-8"));
                    }
                }
                String path = uploadFilePath.substring(uploadFilePath.indexOf("upload"));
                //字段依次是名称，等级，价格，地点，开放时间，介绍，状态
                Attraction attraction = new Attraction(null, fieldList.get(0), Integer.parseInt(fieldList.get(1)),
                        Float.parseFloat(fieldList.get(2)), fieldList.get(3), fieldList.get(4), fieldList.get(5),
                        path+fileName, fieldList.get(6));
                System.out.println(attraction);
                attractionService.addAttraction(attraction);
            } catch (FileUploadException e) {
                throw new RuntimeException(e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
